AWS IAM (Identity and Access Management)
Detailed Content
AWS Identity and Access Management (IAM) enables you to securely control access to AWS services and resources for your users. Using IAM, you can manage who can use your AWS resources (authentication) and what resources they can use and in what ways (authorization).
Core Concepts
- Users: An IAM user is an entity that you create in AWS to represent the person or application that interacts with AWS. Each IAM user has unique security credentials (password for console access, access keys for programmatic access) and can be assigned specific permissions.
- Groups: A collection of IAM users. You can attach policies to a group, and all users in the group inherit the permissions specified by the policies. This simplifies managing permissions for multiple users with similar access needs.
- Roles: An IAM identity that you can create in your account that has specific permissions. An IAM role is similar to an IAM user, but it is intended to be assumable by anyone who needs it (users, services, or applications). Roles do not have standard long-term credentials (password or access keys) associated with them. Instead, temporary security credentials are created dynamically when a role is assumed.
- Policies: Documents that define permissions. Policies are written in JSON and specify actions that are allowed or denied on specific resources under certain conditions. They are the core of IAM authorization.
- Identity-based policies: Attached to an IAM user, group, or role. They grant permissions to the identity.
- Resource-based policies: Attached directly to a resource (e.g., S3 bucket policy, SQS queue policy, KMS key policy). They specify who has access to that resource and what actions they can perform.
- Managed Policies: Standalone identity-based policies that you can attach to multiple principal entities (users, groups, and roles) in your AWS account.
- AWS Managed Policies: Created and managed by AWS (e.g.,
AmazonS3ReadOnlyAccess). AWS updates these policies. - Customer Managed Policies: Created and managed by you. They offer fine-grained control and reusability.
- AWS Managed Policies: Created and managed by AWS (e.g.,
- Inline Policies: Policies that you create and embed directly into a single user, group, or role. They are deleted when the associated identity is deleted.
- Permissions Boundaries: An advanced IAM feature that allows you to set the maximum permissions that an identity-based policy can grant to an IAM entity (user or role). It does not grant permissions itself, but rather limits the permissions that can be granted.
- Service Control Policies (SCPs): A type of organization policy that you can use to manage permissions in your organization in AWS Organizations. SCPs offer central control over the maximum available permissions for all accounts in your organization. They do not grant permissions; instead, they specify the maximum permissions that a user or role can have.
- Multi-Factor Authentication (MFA): An optional but highly recommended security feature that adds an extra layer of protection on top of your username and password. Users provide two or more authentication factors to verify their identity.
- Access Keys: Consist of an access key ID and a secret access key. These are long-term credentials used for programmatic access to AWS (via AWS CLI, SDKs, or direct API calls). They should be treated with the same level of security as a password.
- Policy Evaluation Logic: When a request is made to AWS, IAM evaluates all applicable policies (identity-based, resource-based, SCPs, permission boundaries) to determine if the request is allowed or denied. The general rule is: explicit deny overrides explicit allow; implicit deny is the default.
IAM Best Practices
- Grant Least Privilege: Always grant only the permissions required to perform a specific task. Start with minimal permissions and add more as needed. This minimizes the potential damage if an entity's credentials are compromised.
- Configure a Strong Password Policy: Enforce strong password requirements for IAM users (minimum length, character types, rotation) to prevent unauthorized access.
- Enable MFA for Root Account and IAM Users: Always enable Multi-Factor Authentication for your AWS root account and for all IAM users, especially those with elevated privileges. This adds a critical layer of security.
- Rotate Access Keys Regularly: Regularly rotate access keys for programmatic users to reduce the window of opportunity for compromised keys to be exploited.
- Remove Unused IAM Users and Roles: Periodically review and remove any IAM users, roles, or policies that are no longer needed. This reduces the attack surface.
- Monitor Activity in AWS using CloudTrail: Use AWS CloudTrail to log all API calls and actions taken in your AWS account. Integrate CloudTrail logs with CloudWatch for monitoring and alerting on suspicious activities.
- Use IAM Roles for Applications on EC2 Instances: Instead of storing access keys directly on EC2 instances, use IAM roles. EC2 instances can assume roles to get temporary credentials, which are automatically rotated by AWS, providing a more secure way to grant permissions to applications.
- Use IAM Roles for Cross-Account Access: For granting access to resources in other AWS accounts, use IAM roles instead of sharing user credentials. This allows for temporary, auditable access.
- Validate Policies with IAM Access Analyzer: Regularly use IAM Access Analyzer to identify resources that are shared with external entities, helping you refine your access policies and prevent unintended access.
- Use Permission Boundaries for Delegated Administration: When delegating administrative tasks (e.g., allowing developers to create IAM roles), use permission boundaries to ensure that the roles they create cannot exceed a predefined maximum set of permissions.
- Implement Service Control Policies (SCPs) with AWS Organizations: For multi-account environments, use SCPs to establish guardrails and define the maximum permissions available to IAM users and roles in member accounts. This provides a central control mechanism for security and compliance.
IAM Features
- IAM Access Analyzer: Helps you identify the resources in your organization and accounts, such as S3 buckets or IAM roles, that are shared with an external entity.
- IAM Roles Anywhere: Enables your workloads running outside of AWS to use IAM roles to access AWS resources.
- AWS Organizations: Centrally manage and govern your environment as you grow and scale your AWS resources.
Interview Questions
Conceptual Questions
- What is AWS IAM and what are its core components?
- AWS IAM (Identity and Access Management) enables you to securely control access to AWS services and resources for your users. Its core components are:
- Users: Entities representing people or applications.
- Groups: Collections of users.
- Roles: Identities with permissions that can be assumed by trusted entities.
- Policies: Documents defining permissions (what actions are allowed/denied on what resources).
- AWS IAM (Identity and Access Management) enables you to securely control access to AWS services and resources for your users. Its core components are:
- Explain the difference between an IAM user and an IAM role. When would you use each?
- An IAM User is a persistent identity with long-term credentials (password, access keys) for a single person or application. Use for individual administrators, developers, or specific applications that need their own credentials.
- An IAM Role is an identity with temporary permissions that can be assumed by trusted entities (users, services, or applications). Roles do not have their own credentials. Use roles for EC2 instances to access AWS services, cross-account access, or for temporary elevated privileges.
- Explain the concept of "least privilege" in IAM and why it's a critical security best practice.
- The principle of "least privilege" dictates that you should grant only the minimum permissions required for a user, role, or application to perform its intended task. It's critical because it minimizes the potential damage if an entity's credentials are compromised, reducing the attack surface and limiting unauthorized actions.
- What are the different types of IAM policies? Differentiate between identity-based and resource-based policies.
- Identity-based policies: Attached to an IAM user, group, or role. They define what actions that identity can perform on which resources.
- Resource-based policies: Attached directly to a resource (e.g., S3 bucket policy, SQS queue policy). They specify who (which principal) has access to that specific resource and what actions they can perform.
- Other types include AWS Managed Policies, Customer Managed Policies, and Inline Policies.
- When would you use an AWS managed policy versus a customer managed policy?
- Use AWS Managed Policies for common use cases where AWS has already defined the necessary permissions (e.g.,
AmazonS3ReadOnlyAccess). They are easy to use and maintained by AWS. - Use Customer Managed Policies when you need fine-grained control over permissions that are specific to your organization's needs, or when AWS managed policies grant too many permissions. They offer more flexibility and adhere better to the principle of least privilege.
- Use AWS Managed Policies for common use cases where AWS has already defined the necessary permissions (e.g.,
- What is an IAM Permission Boundary and how does it work?
- An IAM Permission Boundary is an advanced IAM feature that allows you to set the maximum permissions that an identity-based policy can grant to an IAM entity (user or role). It does not grant permissions itself, but rather limits the permissions that can be granted. For example, if a user has a policy allowing S3 full access but their permission boundary only allows S3 read-only, they will only have S3 read-only access.
- Explain Service Control Policies (SCPs) in AWS Organizations. What is their purpose?
- Service Control Policies (SCPs) are a type of organization policy that you can use to manage permissions in your organization in AWS Organizations. SCPs offer central control over the maximum available permissions for all accounts in your organization. They do not grant permissions; instead, they specify the maximum permissions that a user or role can have within an account. They are guardrails to ensure compliance across multiple accounts.
Scenario-Based Questions
- You have an application running on an EC2 instance that needs to access an S3 bucket to read and write files. How would you grant the EC2 instance permission to access the S3 bucket securely and following best practices?
- I would create an IAM Role with a policy that grants the necessary S3 permissions (e.g.,
s3:GetObject,s3:PutObjectfor the specific bucket). Then, I would attach this IAM role to the EC2 instance. This is the most secure and recommended approach because the EC2 instance automatically receives temporary credentials, eliminating the need to store long-term access keys on the instance.
- I would create an IAM Role with a policy that grants the necessary S3 permissions (e.g.,
- A new developer joins your team and needs access to specific AWS resources (e.g., EC2, S3, CloudWatch) for development purposes. You want to manage their permissions efficiently and ensure they only have access to resources tagged for development. How would you set up their access?
- I would create an IAM User for the developer. Then, I would create an IAM Group (e.g.,
Developers) and attach customer-managed policies to this group. These policies would grant permissions to EC2, S3, and CloudWatch, but with resource-level permissions and conditions that restrict access only to resources with a specific tag (e.g.,Environment: Development). I would then add the new developer's IAM user to thisDevelopersgroup. This ensures least privilege and efficient management.
- I would create an IAM User for the developer. Then, I would create an IAM Group (e.g.,
- You want to allow a third-party auditing firm to access your AWS CloudTrail logs and S3 buckets containing application logs, but only for read-only access and only for a limited time. How would you achieve this securely?
- I would create an IAM Role in my AWS account (e.g.,
AuditorAccessRole). This role would have a policy granting read-only access to the specific CloudTrail log groups and S3 buckets. The trust policy of this role would be configured to allow the auditing firm's AWS account to assume this role. I would also add a condition to the trust policy to limit the duration of the session (e.g.,sts:ExternalIdfor cross-account access andsts:DurationSecondsfor session duration). The auditing firm would then assume this role from their account.
- I would create an IAM Role in my AWS account (e.g.,
- Your organization has multiple AWS accounts managed under AWS Organizations. You want to ensure that no IAM user or role in any member account can ever create an EC2 instance in the
us-east-1region, regardless of the IAM policies attached within that account. How would you enforce this?- I would use a Service Control Policy (SCP) in AWS Organizations. I would attach an SCP to the Organizational Unit (OU) or directly to the member accounts that explicitly denies the
ec2:RunInstancesaction when theaws:RequestedRegionisus-east-1. This SCP acts as a guardrail, overriding anyAllowpermissions defined in IAM policies within the member accounts, effectively preventing EC2 instance creation in that region.
- I would use a Service Control Policy (SCP) in AWS Organizations. I would attach an SCP to the Organizational Unit (OU) or directly to the member accounts that explicitly denies the
Coding/CLI Examples
Here are some common IAM operations using the AWS CLI and Python (Boto3).
AWS CLI Examples
-
Create an IAM user and attach an AWS managed policy: ```bash USER_NAME="new-developer-cli"
1. Create IAM user
aws iam create-user --user-name $USER_NAME
2. Attach an AWS managed policy (e.g., AmazonS3ReadOnlyAccess)
aws iam attach-user-policy \ --user-name $USER_NAME \ --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess ```
-
Create an IAM role for an EC2 instance to access S3: ```bash ROLE_NAME="EC2S3RoleCLI"
1. Create a trust policy document (e.g., ec2-trust-policy.json)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"Service": "ec2.amazonaws.com"},
"Action": "sts:AssumeRole"
}
]
}
2. Create the IAM role
aws iam create-role \ --role-name $ROLE_NAME \ --assume-role-policy-document file://ec2-trust-policy.json
3. Attach a policy to the role (e.g., AmazonS3ReadOnlyAccess)
aws iam attach-role-policy \ --role-name $ROLE_NAME \ --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess ```
-
Create a customer-managed policy and attach it to a group: ```bash POLICY_NAME="MyCustomS3ReadWritePolicy" GROUP_NAME="AppAdmins"
1. Create a policy document (e.g., s3-read-write-policy.json)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-app-bucket/*"
}
]
}
2. Create the customer-managed policy
POLICY_ARN=$(aws iam create-policy \ --policy-name $POLICY_NAME \ --policy-document file://s3-read-write-policy.json \ --query 'Policy.Arn' --output text)
3. Create an IAM group
aws iam create-group --group-name $GROUP_NAME
4. Attach the policy to the group
aws iam attach-group-policy \ --group-name $GROUP_NAME \ --policy-arn $POLICY_ARN ```
Python (Boto3) Examples
First, ensure you have Boto3 installed (pip install boto3) and your AWS credentials configured.
-
Create an IAM user and add them to a group: ```python import boto3
iam_client = boto3.client('iam')
user_name = "boto3-developer" group_name = "Boto3Developers"
try: # 1. Create IAM user iam_client.create_user(UserName=user_name) print(f"User {user_name} created.")
# 2. Create IAM group (if it doesn't exist) try: iam_client.get_group(GroupName=group_name) except iam_client.exceptions.NoSuchEntityException: iam_client.create_group(GroupName=group_name) print(f"Group {group_name} created.") # 3. Add user to group iam_client.add_user_to_group(GroupName=group_name, UserName=user_name) print(f"User {user_name} added to group {group_name}.")except Exception as e: print(f"Error creating user or group: {e}") ```
-
Create an IAM role for a Lambda function with a basic execution policy: ```python import boto3 import json import time
iam_client = boto3.client('iam')
role_name = "LambdaExecutionRoleBoto3" policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
assume_role_policy_document = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole" } ] }
try: # 1. Create IAM role create_role_response = iam_client.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps(assume_role_policy_document) ) role_arn = create_role_response['Role']['Arn'] print(f"Role {role_name} created with ARN: {role_arn}")
# 2. Attach policy iam_client.attach_role_policy(RoleName=role_name, PolicyArn=policy_arn) print(f"Policy {policy_arn} attached to role {role_name}.") # IAM eventual consistency time.sleep(10)except Exception as e: print(f"Error creating role or attaching policy: {e}") ```
-
List all IAM users in the account: ```python import boto3
iam_client = boto3.client('iam')
try: response = iam_client.list_users() print("IAM Users:") for user in response['Users']: print(f"- {user['UserName']} (ARN: {user['Arn']})") except Exception as e: print(f"Error listing users: {e}") ```